<?php

namespace addons\hlapp\controller;

use addons\hlapp\dto\Result;
use addons\hlapp\model\HlappMember;
use addons\hlapp\model\HlappPart;
use addons\hlapp\model\HlappProject;
use addons\hlapp\model\HlappProjectEvaluate;
use addons\hlapp\model\HlappProjectRolesMember;
use addons\hlapp\model\HlappProjectStatus;
use think\Db;
use think\Exception;
use think\Log;

class Evaluate extends Common
{
    public $adminLogin = true;//注意：因为这是后台业务菜单所以需要管理员登录操作的
    public $pageSize = 10;

//-------------
//---- 页面
//-------------
    public static $EvaluateColumn= array(
        "项目名称"=>"p_name",
        "坐落位置"=>"p_position",
        "阶段"=>"stage",
        "周数"=>"week",
        "甲方评价人"=>"m_name",
        "评价总状态"=>"status",
        "评价详情"=>"evaluateInfo",
        "备注"=>'e_remark',
        "评价推送时间"=>"time",
    );

    public function test()
    {
        $project = (new HlappProject())->getProject(141);
        return Result::getOk($project);
    }

    /**
     * 分页
     */
    public function pagelist()
    {
        $name = $this->request->param("name");
        $stage = $this->request->param("stage");
        $status = $this->request->param("status");
        $week = $this->request->param("week");
        $year = $this->request->param("year");
        $m = new HlappProjectEvaluate();
        //查询条件：项目名称
        if ($name){
            $pids = "";
            $plist = (new HlappProject())->where('name','like','%'.$name.'%')->select();
            foreach ($plist as $p){
                $pids= $pids.','.$p['id'];
            }
            $m = $m->where('projectId','in',$pids);
        }
        if($stage != null && $stage != ""){
            $m = $m->where('hl_hlapp_project_evaluate.stage',$stage);
        }
        if($status != null && $status != ""){
            if($status == 'null'){
                $m = $m->where('hl_hlapp_project_evaluate.status is null');
            }else{
                $m = $m->where('hl_hlapp_project_evaluate.status',$status);
            }
        }
        if($week != null && $week != ""){
            $m = $m->where('hl_hlapp_project_evaluate.week',$week);
        }
        if($year == null && $year == ""){
            $year = date('Y');
        }
        $m = $m->where("from_unixtime(hl_hlapp_project_evaluate.create_time,'%Y') = ".$year);

        $list = $m->field("hl_hlapp_project_evaluate.*,p.name 'p_name',p.position p_position,m.name 'm_name'")
            ->leftJoin("hlapp_project p","p.id = projectId")
            ->leftJoin("hlapp_member m","m.id = p.amamager_id")
            ->order('id','desc')
            ->paginate($this->pageSize,false,['query'=>request()->param()]);
        $page = request()->param('page');
        $page || ($page=1);
        $this->assign('list', $list);
        $this->assign('name',$name);
        $this->assign('page',$page);
        $this->assign('stage',$stage);
        $this->assign('status',$status);
        $this->assign('week',$week);
        if ($year == date('Y')){
            $year = null;
        }
        $this->assign('year',$year);
        return $this->fetch();
    }


    /**
     * 添加方法
     */
    public function add(){

        $r =  Result::getError();
        try{
            Db::startTrans();
            $p = new HlappProject();
            $r = $p->addProject();
            $pr = json_decode($r);
            if($pr->code == 1){
                $pId = $pr->result;
                $parts = $_POST['parts'];
                for ($i = 0;$i<count($parts);$i++){
                    $parts[$i]['p_id'] = $pId;
                }
                foreach ($parts as $part){
                    $m = new HlappProjectRolesMember($part);
                    $m->allowField(true)->save();
                }
            }
            Db::commit();
            $r = Result::getOk();
        }catch (\Exception $e){
            Db::rollback();
            $r =  Result::getError();
        }
        return $r;
    }
    /**
     * 删除方法
     */
    public function delete(){
        $r = Result::getError();
        try{
            $id = $_POST['id'];
            $p = HlappProjectEvaluate::get($id);
//            $p->together('rolesMember')->delete();
            $p->delete();
            $r = Result::getOk();
        }catch (Exception $e){

        }
        return $r;

    }
    /**
     * 更新页面
     */
    public function updatepage(){
        $id = $_GET['id'];
        $project = (new HlappProject())->getProject($id);
        $this->assign('project',$project);
        $parts = (new HlappPart())->with('members')->select();
        $this->assign('parts',$parts);
        return $this->fetch();
    }
    /**
     * 更新方法
     */
    public function update(){
        $id = $_POST['id'];
        $r =  Result::getError();
        try{
            Db::startTrans();
            $p = HlappProject::get($id);
            $r = $p->field($_POST)->allowField(true)->save();
//            $pr = json_decode($r);
 /*           if($pr->code == 1){
                $pId = $pr->result;exportExl
                $parts = $_POST['parts'];
                for ($i = 0;$i<count($parts);$i++){
                    $m = HlappProjectRolesMember::where('p_id',$id)
                        ->where('r_id',$parts[$i]['r_id'])->find();
                    $m->field($parts[$i])->allowField()->save();
                }
            }*/
            Db::commit();
            $r = Result::getOk();
        }catch (\Exception $e){
            Db::rollback();
            $r =  Result::getError("更新失败！");
        }
        return $r;
    }

    /**
     * 导出表格
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportExl(){
        $name = $this->request->param("name");
        $stage = $this->request->param("stage");
        $status = $this->request->param("status");
        $week = $this->request->param("week");
        $whereSql = "";
        //查询条件：项目名称
        if ($name){
            $pids = "";
            $plist = (new HlappProject())->where('name','like','%'.$name.'%')->select();
            foreach ($plist as $p){
                $pids= $pids.','.$p['id'];
            }
            $whereSql = $whereSql." and p.name like '%".$name."%'";
        }
        if($stage != null && $stage != ""){
            $whereSql = $whereSql." and e.stage = ".$stage;
        }
        if($status != null && $status != ""){
            if ($status == 'null'){
                $whereSql = $whereSql." and e.status  is ".$status;
            }else{
                $whereSql = $whereSql." and e.status = ".$status;
            }
        }
        if($week != null && $week != ""){
            $whereSql = $whereSql." and e.week = ".$week;
        }

        $sql="select 
                case e.`status`
                    when 1 then '满意'
                    when 0 then '不满意'
                end 'status',
                case e.stage
                    when 0 then '样板房'
                    when 1 then '前期进场'
                    when 2 then '前期施工'
                    when 3 then '施工过程'
                    when 4 then '施工收尾'
                    when 5 then '售后维修'
                end 'stage',
                m.name 'm_name',
                e.week 'week',
                p.name 'p_name',
                p.position 'p_position',
                e.remark 'e_remark',
                (
                select 
                REPLACE(REPLACE(REPLACE(e.evaluateInfo,'{\"key\":\"',\"\"),'\",\"value\"',\"\"),'}','')
                from hl_hlapp_project_evaluate ee where ee.id = e.id
                ) 'evaluateInfo',
                from_unixtime(e.update_time,'%Y-%m-%d') 'time' 
                from hl_hlapp_project_evaluate e
                left join hl_hlapp_project p on p.id = e.projectId
                left join hl_hlapp_member m on m.id = p.amamager_id
                where e.delete_time is null
                ".$whereSql."
                order by e.id desc
                ";
        \Log::INFO($sql);
        $list = Db::query($sql);

        $path=$this->exportExcel('evaluate',self::$EvaluateColumn,$list);
        return Result::getOk($path);
    }

}